我們利用TCP Listener來監聽 Port,通過 Socket 及 Stream 來傳送接收封包(Packet),並且採用非同步的方式處理網路連線,來與各玩家(Client)做資料傳輸,在伺服器來做統一的運算處理並將處理後的結果發送給單一或是多個玩家(Client)。
public static void Start(int _maxPlayers, int _port)
{
tcpListener = new TcpListener(IPAddress.Any, Port);
tcpListener.Start();
tcpListener.BeginAcceptTcpClient(TCPConnectCallback, null);
}
在伺服器關閉時,也同時取消TCP的監聽
public static void Stop()
{
tcpListener.Stop();
}
在Client端建立TCP的Class並在Client這個Script裡,來做TCP的連線
public class TCP
{
public TcpClient socket;
private NetworkStream stream;
private Packet receivedData;
private byte[] receiveBuffer;
/// <summary>Attempts to connect to the server via TCP.</summary>
public void Connect()
{
socket = new TcpClient
{
ReceiveBufferSize = dataBufferSize,
SendBufferSize = dataBufferSize
};
receiveBuffer = new byte[dataBufferSize];
socket.BeginConnect(instance.ip, instance.port, ConnectCallback, socket);
}
}